% This script computes the tactical asset allocation at the investment horizon 
% and performs the comparison with the strategic allocation.
% For more details go to "www.gerardoferrara.com", by G. Ferrara.

clc; clear; close all;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [AA,BB]=BL(x) 

MKT_NEUTRAL=[0.1 0.55 0.05 0.093 0.144 0.03 0.012 0.021]';

RETURNS=xlsread('database.xls', 'Series','b2:i22')

COV=cov(RETURNS);

RISK_FREE=0.03;

VAR_NEUTR=MKT_NEUTRAL'*COV*MKT_NEUTRAL;


MACRO_PREMIUM=[0 0.003 0.0045 0.045 0.045 0.045 0.045 0.045];


LAMDA_CHOSE=(MKT_NEUTRAL'*MACRO_PREMIUM')/VAR_NEUTR;

EXP_RET_MKT_NEUTRAL_END=COV*MKT_NEUTRAL*LAMDA_CHOSE+RISK_FREE;



TAU=1/21;


P=[0 0 0 0 -1 1 0 0;
    0 0 0 1 0 0 0 0];

Q=[0.04; 0.09];


C=[0.04;0.04];

OMEGA=[(1/C(1,1)-1)*P(1,:)*TAU*COV*P(1,:)', 0;0, (1/C(2,1)-1)*P(2,:)*TAU*COV*P(2,:)'];

REND_BLACK_LITTERMAN=(inv(inv(TAU*COV)+P'*inv(OMEGA)*P))*(inv(TAU*COV)*EXP_RET_MKT_NEUTRAL_END+P'*inv(OMEGA)*Q);

COMPAR_REND_ATT=[EXP_RET_MKT_NEUTRAL_END REND_BLACK_LITTERMAN];



[RISK1 RETURN1 WEIGHTS1]=portopt(REND_BLACK_LITTERMAN,COV, 100);





PESI_STRATEGICI=WEIGHTS1(30,:);

[NUN, NUN1, NAMETEXT]=xlsread('database','Series','B1:I1');


figure(1)
pie(PESI_STRATEGICI)
title('Strategic Asset Allocation')
legend1 = legend(NAMETEXT,'Location','SouthOutside')
hold on

x0=PESI_STRATEGICI;

RENDIMENTI_TATTICI=REND_BLACK_LITTERMAN;
RENDIMENTI_TATTICI(5,1)=REND_BLACK_LITTERMAN(5,1)-0.005;
RENDIMENTI_TATTICI(8,1)=REND_BLACK_LITTERMAN(8,1)+0.005;

COMPAR=[REND_BLACK_LITTERMAN RENDIMENTI_TATTICI];
figure(2)
bar(COMPAR)
title('E(R) Strategic versus Tactical')


PREMIO_RISCHIO_TATTICO=(RENDIMENTI_TATTICI-RISK_FREE);


objfun=@(x1) -x1*RENDIMENTI_TATTICI;


Aeq=ones(8,1)';
beq=[1];

u_bound=ones(8,1);
l_bound=zeros(8,1);



function [c,ceq]=constr(x1); 
ceq=[];
c=[-((x1*PREMIO_RISCHIO_TATTICO)/(x1*COV*x1'))+LAMDA_CHOSE];
end

options=optimset('LargeScale','off','MaxFunEvals',1000000);


[x1,fval] =fmincon(objfun,x0,[],[], Aeq,beq,l_bound,u_bound, @constr, options)


COMPAR2=x1-PESI_STRATEGICI

figure(3)
barh(COMPAR2)
title('Tactical versus Strategic')
grid on


REVAR=COMPAR2*REND_BLACK_LITTERMAN-norminv(0.98,0,1)*sqrt(COMPAR2*COV*COMPAR2')

REVAR2=COMPAR2*REND_BLACK_LITTERMAN-norminv(0.95,0,1)*sqrt(COMPAR2*COV*COMPAR2')

REVAR_TOT=[REVAR ;REVAR2];


figure(4)
barh(REVAR_TOT)
title('Relative VaR (Conf lev 0.95 & 0.98)')
grid on


end
